package com.tools.cleanmaster.ui.activity;

import android.app.KeyguardManager;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.daps.weather.weathercard.DapWeatherView;
import com.hm.base.android.ui.util.ScreenUtil;
import com.tools.ad.util.FontUtils;
import com.tools.ad.util.StatusBarUtil;
import com.tools.ad.util.WindowLayoutParamsUtil;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.functionpage.FunctionItem;
import com.tools.cleanmaster.functionpage.FunctionItemSharedPrefs;
import com.tools.cleanmaster.manager.ChargingManager;
import com.tools.cleanmaster.ui.base.SingleActivity;
import com.tools.cleanmaster.ui.view.CircleProgress;
import com.tools.cleanmaster.ui.view.SlideBackLayout;
import com.tools.cleanmaster.ui.view.SlideUnlockHintView;
import com.tools.cleanmaster.utils.ImageUtil;
import com.tools.cleanmaster.utils.MemoryUtils;
import com.tools.cleanmaster.utils.StorageUtils;

import java.util.Calendar;
import java.util.Locale;

/**
 * desc:
 * date: 2018/3/1
 * author: ancun
 */

public class SmartChargingActivity extends SingleActivity implements SlideBackLayout.OnSlidingFinishListener, View.OnClickListener {

    public static final String SMART_CHARGING_LAUNCH_FLAG = "smart_charging_launch_flag";

    private ViewGroup mRootView;
    private SlideBackLayout mSmartChargingContainer;

    //private ViewGroup mBatteryLayout;
    private ViewGroup mCpuLayout;
    private ViewGroup mMemoryLayout;
    private ViewGroup mBatteryLayout;

    private SlideUnlockHintView mSlideUnlockHintView;
    private RelativeLayout mWeatherContainer;
    private DapWeatherView mDuWeatherView;

    private TextView mTime;
    private TextView mDate;

    private TextView mStorageTitle;
    private TextView mMemoryTitle;

    private TextView mMemoryValue;
    private TextView mStorageValue;
    private CircleProgress mBatteryView;
    private ImageView mToolMenu;

    private PopupWindow mPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_smart_charging);
        setWindowLayoutParams();
        setStatusBar();

        initView();
        initBackGround();
        initWeatherView();

    }

    private void setWindowLayoutParams() {
        int flag = getIntent().getIntExtra(SMART_CHARGING_LAUNCH_FLAG, 0);
        WindowLayoutParamsUtil.setWindowShowWhenLocked(this, flag == ChargingManager.FLAG_TURN_SCREEN_ON);
    }

    private void setStatusBar() {
        StatusBarUtil.setTranslucent(this, 30);
    }

    private void initView() {
        mRootView = findViewById(R.id.root);
        mSmartChargingContainer = findViewById(R.id.smart_charging_container);
        mSlideUnlockHintView = findViewById(R.id.slide_unlock_view);
        mSmartChargingContainer.setTouchView(mSmartChargingContainer);
        mSmartChargingContainer.setOnSlidingFinishListener(this);

        mWeatherContainer = findViewById(R.id.weather_container);

        mTime = findViewById(R.id.smart_charging_time);
        mTime.setTypeface(FontUtils.getInstance(imContext).getRobotThin());
        mDate = findViewById(R.id.smart_charging_date);
        mDate.setTypeface(FontUtils.getInstance(imContext).getRoboLight());

        mMemoryLayout = findViewById(R.id.memory_layout);
        mMemoryLayout.setOnClickListener(this);

        mCpuLayout = findViewById(R.id.storage_layout);
        mCpuLayout.setOnClickListener(this);

        mBatteryLayout = findViewById(R.id.battery_layout);
        mBatteryLayout.setOnClickListener(this);

        mMemoryValue = findViewById(R.id.memory_value);
        mStorageValue = findViewById(R.id.storage_value);
        mBatteryView = findViewById(R.id.battery_view);

        mToolMenu = findViewById(R.id.tool_menu);
        mToolMenu.setOnClickListener(this);

        mStorageTitle = findViewById(R.id.storage_title);
        mMemoryTitle = findViewById(R.id.memory_title);
    }

    private void initBackGround() {
        // 获取壁纸管理器
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
        // 获取当前壁纸
        Drawable wallpaperDrawable = null;
        try {
            wallpaperDrawable = wallpaperManager.getDrawable();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (wallpaperDrawable != null) {
                // 将Drawable,转成Bitmap
                Bitmap bm = ((BitmapDrawable) wallpaperDrawable).getBitmap();
                // 进行高斯模糊、缩放、亮度调节
                Bitmap bitmap = ImageUtil.convertToBlurAndBright(this, bm);
                // 设置背景
                mRootView.setBackground(new BitmapDrawable(getResources(), bitmap));
            } else {
                mRootView.setBackgroundColor(Color.argb(200, 0, 0, 0));
            }
        } catch (Throwable e) {
            mRootView.setBackgroundColor(Color.argb(200, 0, 0, 0));
            //e.printStackTrace();
        }
    }

    private void initWeatherView() {
        try {
            mWeatherContainer.removeAllViews();
            mDuWeatherView = new DapWeatherView(this);
            mWeatherContainer.addView(mDuWeatherView);
            mDuWeatherView.load();
            View child = mDuWeatherView.getChildAt(0);
            child.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDuWeatherView.onClick(v);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !isFinishing()) {
                        finish();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        int i = v.getId();
        if (i == R.id.memory_layout) {
            intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

            if (!isFinishing()) {
                finish();
            }


        } else if (i == R.id.storage_layout) {
            intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

            if (!isFinishing()) {
                finish();
            }

        } else if (i == R.id.battery_layout) {
            FunctionItem item = FunctionItemSharedPrefs.getFunctionItemNormal(imContext, FunctionItem.BATTERY) ? FunctionItem.BATTERY : FunctionItem.BATTERYOVER;
            intent = new Intent(this, FunctionPageGuideActivity.class);
            intent.putExtra(FunctionPageGuideActivity.ITEM_EXTEA_FLAG, item.toString());
            startActivity(intent);

            if (!isFinishing()) {
                finish();
            }

        } else if (i == R.id.tool_menu) {
            showPopUp(mToolMenu);

        } else if (i == R.id.menu_setting) {
            intent = new Intent(SmartChargingActivity.this, ChargingSettingActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);

            mPopupWindow.dismiss();

            if (!isFinishing()) {
                finish();
            }
        }
    }

    private void showPopUp(View v) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.smart_charging_menu, null);
        contentView.findViewById(R.id.menu_setting).setOnClickListener(this);
        mPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources()));
        mPopupWindow.showAsDropDown(v, -(ScreenUtil.dp2px(imContext, 40)), ScreenUtil.dp2px(imContext, 4));
    }

    @Override
    public void subHandleMessage(Message msg) {
        if (msg.what == R.id.msg_cleaner_hide_smart_charging_view) {
            if (!isFinishing()) {
                finish();
            }

        } else if (msg.what == R.id.msg_cleaner_smart_charging_update_info) {
            updateDisplayInfo();
            sendEmptyMessage(R.id.msg_cleaner_smart_charging_update_info, 5000);
        }
    }

    @Override
    protected void doOnResume() {
        super.doOnResume();
        mSlideUnlockHintView.start();
        sendEmptyMessage(R.id.msg_cleaner_smart_charging_update_info);
    }

    @Override
    protected void doOnPause() {
        super.doOnPause();
        mSlideUnlockHintView.stop();
        removeEmptyMessage(R.id.msg_cleaner_smart_charging_update_info);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSlideUnlockHintView.destory();
        dismissKeyguard();
    }

    @Override
    public void onSlidingFinish() {
        if (!isFinishing()) {
            finish();
        }
    }

    private void dismissKeyguard() {
        boolean isNeedDismissKeyguard = true;
        try {
            KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
            isNeedDismissKeyguard = keyguardManager.isKeyguardSecure();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //如果是如滑动解锁等不需要密码的，不用执行以下代码
        if (isNeedDismissKeyguard) {
            Intent localIntent = new Intent(this, DismissKeyguardActivity.class);
            localIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(localIntent);
        }
    }

    private void updateDisplayInfo() {
        mTime.setText(getCurrentTime());
        mDate.setText(getWeekDayMonth());

        float usedStoragePercent = StorageUtils.getUsedStoragePercent(this);
        mStorageValue.setText((int) (usedStoragePercent * 100) + "%");
        mStorageValue.setTextColor(Color.WHITE);

        int batteryPct = imContext.getChargingManager().getBatteryPct();
        mBatteryView.setProgress(batteryPct);
        mBatteryView.setTextColor(Color.WHITE);

        float usedMemoryPercent = MemoryUtils.getUsedMemoryPercent(this);
        mMemoryValue.setText((int) (usedMemoryPercent * 100) + "%");
        mMemoryValue.setTextColor(Color.WHITE);

        mStorageTitle.setTextColor(Color.WHITE);
        mMemoryTitle.setTextColor(Color.WHITE);
    }

    private String getWeekDayMonth() {
        long curTime = System.currentTimeMillis();
        String date = DateUtils.formatDateTime(imContext, curTime, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH);
        String weekDay = DateUtils.formatDateTime(imContext, curTime, DateUtils.FORMAT_SHOW_WEEKDAY);
        return weekDay + ", " + date;
    }

    private String getCurrentTime() {
        Calendar calendar = Calendar.getInstance();
        String timeFormat = String.format(Locale.ENGLISH, "%02d:%02d", calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE));
        return timeFormat;
    }

}
